package com.tuanzi.loan.web.bean.templateConf;

import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.templateConf.*;
import com.tuanzi.loan.business.service.templateConf.ActivityItemService;
import com.tuanzi.loan.business.service.templateConf.ActivityService;
import com.tuanzi.loan.business.service.templateConf.TemplateItemOptionService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.primefaces.event.RowEditEvent;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 甲方模板项配置
 */
@Debug
@Component
@ViewScoped
@Data
@EqualsAndHashCode(callSuper = true)
public class ActivityItemListBean extends JSFInfoBean<LoanApiActivityEntity> {

    private static final long serialVersionUID = -7456998959122405455L;

    @Autowired
    private ActivityItemService activityItemService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private TemplateItemOptionService templateItemOptionService;

    //一级页面
    private List<LoanApiModelItemEntity> itemList; //甲方模板项列表
    private List<LoanApiThirdEntity> thirdList;  //甲方列表
    private List<LoanApiModelPageEntity> modelPageList; //栏目列表
    private List<LoanApiModelItembasisEntity> allModelItemBasisList; //模板一级项列表
    private List<LoanApiModelItembasisEntity> apiModelItemBasisList; //甲方已配的模板一级项列表
    //二级页面
    private LoanApiModelItemEntity currentItem; //当前编辑的一级项
    private List<LoanApiModelItemOptionEntity> modelItemOptionList; //甲方模板二级项列表
    private List<LoanApiModelItemOptionbasisEntity> modelItemOptionBasisList; //模板二级项列表
    private List<LoanApiModelValiRuleEntity> modelValiRuleList; //甲方模板项检验规则列表
    private List<LoanApiModelValidateEntity> modelValidateList; //检验规则列表

    @PostConstruct
    private void init() {
        initLazyDataModel();
    }

    private void initLazyDataModel() {
        String apiId = getParamFromRequest("id");
        if (StringUtils.isNotBlank(apiId)) {
            long longApiId = NumberUtils.toLong(apiId);
            $ = activityService.findOne(longApiId);
            itemList = activityItemService.findByApiId(longApiId);
            apiModelItemBasisList = activityItemService.getModelItemBasisListByApiId(longApiId);
        } else {
            $ = new LoanApiActivityEntity();
            itemList = new ArrayList<>();
        }
        thirdList = activityItemService.getThirdList();
        modelPageList = activityItemService.getModelPageList();
        allModelItemBasisList = activityItemService.getModelItemBasisList();
    }

    //保存表单
    public void onSave() {
        if (StringUtils.isBlank($.getApiName())) {
            addInfoMessage("请填写模板名称");
            return;
        }
        //保存模板
        Long thirdId = $.getThirdId();
        if (thirdId != -1) {
            LoanApiThirdEntity loanApiThirdEntity = activityItemService.findByThirdId(thirdId);
            $.setThirdName(loanApiThirdEntity.getThirdName());
        }
        String name = CurrentUser.get().getName();
        $.setUserName(name);
        $ = activityService.saveOrUpdate($);

        //保存模板项
        if (CollectionUtils.isNotEmpty(itemList)) {
            for (LoanApiModelItemEntity loanApiModelItemEntity : itemList) {
                loanApiModelItemEntity.setHaveParent((short) (loanApiModelItemEntity.getParentItemId() != null?1:0));
                loanApiModelItemEntity.setApiId($.getId());
                activityItemService.saveOrUpdate(loanApiModelItemEntity);
            }
        }
        addSuccessfullyMessage();
    }

    //复制并保存表单
    public String onCopySave(Long apiId) {
        //初始化数据
        $ = activityService.findOne(apiId);
        itemList = activityItemService.findByApiId(apiId);

        //复制模板
        LoanApiActivityEntity activityEntity = new LoanApiActivityEntity();
        BeanUtils.copyProperties($, activityEntity);
        activityEntity.setId(null);
        String name = CurrentUser.get().getName();
        activityEntity.setUserName(name);
        $ = activityService.saveOrUpdate(activityEntity);

        //复制模板项
        if (CollectionUtils.isNotEmpty(itemList)) {
            Map<Long, Long> oldIdToNewIdMap= new HashMap<>();  //存储旧子项与新子项的关系，用于查找到新父项
            List<LoanApiModelItemEntity> newItemList = new ArrayList<>();  //用于更新父项
            for (LoanApiModelItemEntity oldItemEntity : itemList) {
                Long itemId = oldItemEntity.getId();
                LoanApiModelItemEntity newItemEntity = new LoanApiModelItemEntity();
                BeanUtils.copyProperties(oldItemEntity, newItemEntity);
                newItemEntity.setId(null);
                newItemEntity.setHaveParent((short) (newItemEntity.getParentItemId() != null?1:0));
                newItemEntity.setApiId($.getId());
                newItemEntity = activityItemService.saveOrUpdate(newItemEntity);
                oldIdToNewIdMap.put(itemId, newItemEntity.getId());
                newItemList.add(newItemEntity);

                //复制二级模板项
                modelItemOptionList = activityItemService.getModelItemOptionListByItemId(itemId);
                for (LoanApiModelItemOptionEntity itemOptionEntity : modelItemOptionList) {
                    LoanApiModelItemOptionEntity newItemOptionEntity = new LoanApiModelItemOptionEntity();
                    BeanUtils.copyProperties(itemOptionEntity, newItemOptionEntity);
                    newItemOptionEntity.setId(null);
                    newItemOptionEntity.setItemId(newItemEntity.getId());
                    activityItemService.saveModelItemOption(newItemOptionEntity);
                }

                //复制一级校验规则
                modelValiRuleList = activityItemService.getModelValiRuleListByItemId(itemId);
                for (LoanApiModelValiRuleEntity valiRuleEntity : modelValiRuleList) {
                    LoanApiModelValiRuleEntity newValiRuleEntity = new LoanApiModelValiRuleEntity();
                    BeanUtils.copyProperties(valiRuleEntity, newValiRuleEntity);
                    newValiRuleEntity.setId(null);
                    newValiRuleEntity.setItemId(newItemEntity.getId());
                    activityItemService.saveModelValiRule(newValiRuleEntity);
                }
            }
            //替换新的父项
            for (LoanApiModelItemEntity loanApiModelItemEntity : newItemList) {
                if(loanApiModelItemEntity.getParentItemId() != null && loanApiModelItemEntity.getParentItemId() != 0){
                    loanApiModelItemEntity.setParentItemId(oldIdToNewIdMap.get(loanApiModelItemEntity.getParentItemId()));
                    activityItemService.saveOrUpdate(loanApiModelItemEntity);
                }
            }
        }
        return redirect("/views/templateConf/activityConf/activityItemList?id=" + $.getId());
    }

    //编辑行
    public void onRowEdit(RowEditEvent event) {
        if (StringUtils.isBlank($.getApiName())) {
            addInfoMessage("请填写模板名称并点击保存");
            return;
        }
        LoanApiModelItemEntity entity = (LoanApiModelItemEntity) event.getObject();
        entity.setHaveParent((short) (entity.getParentItemId() != null?1:0));
        activityItemService.saveOrUpdate(entity);
        addSuccessfullyMessage();
    }

    //删除行
    public void onRowCancel(RowEditEvent event) {
        LoanApiModelItemEntity entity = (LoanApiModelItemEntity) event.getObject();
        if (entity.getId() != null) {
            activityItemService.delete(entity.getId());
        }
        //itemList = itemList.stream().filter(a -> !a.getId().equals(entity.getId())).collect(Collectors.toList());
        forceRedirect("/views/templateConf/activityConf/activityItemList.xhtml?id=" + $.getId());
        //addSuccessfullyMessage();
    }

    //新增一行
    public void onAddNew(Long apiId) {
        LoanApiModelItemEntity entity = new LoanApiModelItemEntity();
        entity.setId(null);
        entity.setApiId(apiId);
        itemList.add(entity);
    }

    //==========================编辑二级项==============================
    public void onEditSecond(Long itemId){
        currentItem = activityItemService.findOne(itemId);
        modelItemOptionList = activityItemService.getModelItemOptionListByItemId(itemId);
        modelItemOptionBasisList = templateItemOptionService.findByItembasisId(currentItem.getItemBasisId());
    }
    public void onItemOptionRowEdit(RowEditEvent event) {
        LoanApiModelItemOptionEntity entity = (LoanApiModelItemOptionEntity) event.getObject();
        activityItemService.saveModelItemOption(entity);
        addSuccessfullyMessage();
    }
    public void onItemOptionRowCancel(RowEditEvent event) {
        LoanApiModelItemOptionEntity entity = (LoanApiModelItemOptionEntity) event.getObject();
        if (entity.getId() != null) {
            activityItemService.deleteModelItemOptionById(entity.getId());
        }
        //modelItemOptionList = modelItemOptionList.stream().filter(a -> !a.getId().equals(entity.getId())).collect(Collectors.toList());
        forceRedirect("/views/templateConf/activityConf/activityItemList.xhtml?id=" + $.getId());
        //addSuccessfullyMessage();
    }
    public void onItemOptionAddNew(Long itemId) {
        LoanApiModelItemOptionEntity entity = new LoanApiModelItemOptionEntity();
        entity.setId(null);
        entity.setItemId(itemId);
        modelItemOptionList.add(entity);
    }

    //==========================编辑校验规则==============================
    public void onValiRule(Long itemId){
        currentItem = activityItemService.findOne(itemId);
        modelValiRuleList = activityItemService.getModelValiRuleListByItemId(itemId);
        modelValidateList = activityItemService.getModelValidateList();
    }
    public void onValiRuleRowEdit(RowEditEvent event) {
        LoanApiModelValiRuleEntity entity = (LoanApiModelValiRuleEntity) event.getObject();
        activityItemService.saveModelValiRule(entity);
        addSuccessfullyMessage();
    }
    public void onValiRuleRowCancel(RowEditEvent event) {
        LoanApiModelValiRuleEntity entity = (LoanApiModelValiRuleEntity) event.getObject();
        if (entity.getId() != null) {
            activityItemService.deleteModelValiRuleById(entity.getId());
        }
        forceRedirect("/views/templateConf/activityConf/activityItemList.xhtml?id=" + $.getId());
        //modelValiRuleList = modelValiRuleList.stream().filter(a -> !a.getId().equals(entity.getId())).collect(Collectors.toList());
        //addSuccessfullyMessage();
    }
    public void onValiRuleAddNew(Long itemId) {
        LoanApiModelValiRuleEntity entity = new LoanApiModelValiRuleEntity();
        entity.setId(null);
        entity.setItemId(itemId);
        modelValiRuleList.add(entity);
    }

}
